/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/jims/mpa">mpa</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.jims.master.common.utils;


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转拼音工具类
 *
 * @author wumengxiang
 * @version 2015-05-6
 */
public class PinyinUtils {
    public static void main(String [] args){

//        System.out.println(PinyinUtils.getPinyinAll("汉字转拼音工具类"));
        System.out.println(PinyinUtils.getPinyinFirst("你k从来没在我脑子里休息过，你累不累"));
    }

    /**
     * 得到汉字全拼
     *
     * @param chinese
     * @return pinyinAll
     */
    public static String getPinyinAll(String chinese){
        char[] t1 = null;
        t1 = chinese.toCharArray();
        String[] t2 = new String[t1.length];

        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE); //小写
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE); //无音标
        t3.setVCharType(HanyuPinyinVCharType.WITH_V); //用v表示lv

        String t4 = "";
        int t0 = t1.length;

        try {
            for (int i = 0; i < t0; i++) {
                //判断是否为汉字
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    t4 += t2[0];
                }else{
                    t4 += Character.toString(t1[i]);
                }
            }
        }catch (BadHanyuPinyinOutputFormatCombination el) {
            el.printStackTrace();
        }
        return t4;
    }


    /**
     * 得到汉字首拼
     *
     * @param chinese
     * @return pinyinFirst
     */
    public static String getPinyinFirst(String chinese){
        String convert = "";
        for(int i = 0;i < chinese.length();i++){
            char word = chinese.charAt(i);

            String [] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if(pinyinArray != null){
                convert += pinyinArray[0].charAt(0);
            }else{
                convert += word;
            }
        }
        return convert;
    }
}
